package com.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.system.pojo.Contact;
import com.system.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class ContactController {
    @Autowired
    private ContactService contactService;

    @RequestMapping("selectContactForPage")
    @ResponseBody
    public String selectContactForPage(Contact contact, @RequestParam(defaultValue="1")int page, @RequestParam(defaultValue="5")int limit){
        List<Contact> list   = contactService.selectContact(contact);
        List<Contact> people = contactService.selectContactByPage(contact,page, limit);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("count",list.size());
        jsonObject.put("data", people);
        jsonObject.put("msg", "查询成功");
        return jsonObject.toJSONString();
    }

    @RequestMapping("delContact")
    @ResponseBody
    public String delContact(Contact contact){
        JSONObject jsonObject = new JSONObject();
        Integer personId = contact.getPersonId();
        try {
            contactService.delContact(personId);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "删除成功");
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "删除失败");
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping("updateContact")
    @ResponseBody
    public String selectContactForPersonId(Contact contact){
        JSONObject jsonObject = new JSONObject();
        try {
            contactService.updateContact(contact);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "修改成功");
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "修改失败");
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping("insertContact")
    @ResponseBody
    public String insertContact(Contact contact, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        JSONObject jsonObject = new JSONObject();
        if (cookies!=null){
            System.out.println(cookies);
        }
        try {
            contactService.insertContact(contact);
            jsonObject.put("code", 0);
            jsonObject.put("msg", "查询成功");
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "删除失败");
        }
        return jsonObject.toJSONString();
    }
}
